var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
import { useEffect, useRef, useState } from "react";
import Taro, { createSelectorQuery, getSystemInfoSync } from "@tarojs/taro";
export function useVirtualList(_a) {
    var data = _a.data, pageNo = _a.pageNo, _b = _a.segmentNum, segmentNum = _b === void 0 ? 20 : _b, _c = _a.screenNum, screenNum = _c === void 0 ? 2 : _c, _d = _a.listId, listId = _d === void 0 ? "zt-virtial-list" : _d, scrollViewProps = _a.scrollViewProps;
    var _e = __read(useState([]), 2), twoList = _e[0], setTwoList = _e[1]; // 二维数组
    var windowHeight = useRef(getSystemInfoSync().windowHeight); // / 当前屏幕的高度
    var twoListRef = useRef([]); // 缓存twoList，因为小程序observe回调里面无法拿到最新的state
    var initList = useRef([]); // 承载初始化的二维数组
    var pageHeightArr = useRef([]); // 用来装每一屏的高度
    var currentPage = useRef(Taro.getCurrentInstance()); // 当前页面实例
    useEffect(function () {
        formatMultiList(data);
    }, [data]);
    useEffect(function () {
        twoListRef.current = __spread(twoList);
    }, [twoList]);
    /**
     * 当list是通过服务端分页获取的时候，对list进行处理
     * @param  list 外部list
     * @param  pageNum 当前页码
     */
    var formatMultiList = function (list) {
        if (list === void 0) { list = []; }
        if (!(list === null || list === void 0 ? void 0 : list.length))
            return;
        var pageNum = Math.max(pageNo - 2, 0); // 每一屏为一个单位，屏幕索引
        segmentList(list); // 分割列表
        twoList[pageNum] = initList.current[pageNum];
        setTwoList(__spread(twoList));
        /** 因为异步刷新，可能无法在个时间片获取最新节点数据，所以逻辑移动到useEffect中 */
        // Taro.nextTick(() => {
        //     setHeight();
        //   });
    };
    useEffect(function () {
        if (!twoList.length)
            return;
        setHeight();
    }, [twoList]);
    /**
     * 设置每一个维度的数据渲染完成之后所占的高度
     */
    var setHeight = function () {
        var wholePageIndex = Math.max(pageNo - 2, 0); // 每一屏为一个单位，屏幕索引
        if (pageHeightArr.current[wholePageIndex])
            return;
        var query = createSelectorQuery();
        query.select("#" + listId + " .wrap_" + wholePageIndex).boundingClientRect();
        query.exec(function (res) {
            var _a, _b;
            console.log("res", res);
            // 有数据的时候才去收集高度，不然页面初始化渲染（在H5中无数据）收集到的高度是错误的
            if (((_a = initList.current) === null || _a === void 0 ? void 0 : _a.length) && ((_b = res === null || res === void 0 ? void 0 : res[0]) === null || _b === void 0 ? void 0 : _b.height)) {
                // pageHeightArr.current.push(res[0].height);
                pageHeightArr.current[wholePageIndex] = res[0].height;
            }
        });
        miniObserve();
    };
    /**
     * 按规则分割list，存在initList上，备用
     */
    var segmentList = function (list) {
        if (list === void 0) { list = []; }
        var arr = [];
        var _list = [];
        list.forEach(function (item, index) {
            arr.push(item);
            if ((index + 1) % segmentNum === 0) {
                _list.push(arr);
                arr = [];
            }
        });
        // 将分段不足segmentNum的剩余数据装入_list
        if (arr.length) {
            _list.push(arr);
        }
        initList.current = _list;
    };
    /**
     * 小程序平台监听
     */
    var miniObserve = function () {
        var _a;
        var currentIndex = Math.max(pageNo - 2, 0);
        // 以传入的scrollView的高度为相交区域的参考边界，若没传，则默认使用屏幕高度
        var scrollHeight = ((_a = scrollViewProps === null || scrollViewProps === void 0 ? void 0 : scrollViewProps.style) === null || _a === void 0 ? void 0 : _a.height) || windowHeight.current;
        var observer = Taro.createIntersectionObserver(currentPage.current.page).relativeToViewport({
            top: screenNum * scrollHeight,
            bottom: screenNum * scrollHeight
        });
        observer.observe("#" + listId + " .wrap_" + currentIndex, function (res) {
            var _a;
            var twoList = twoListRef.current;
            if ((res === null || res === void 0 ? void 0 : res.intersectionRatio) <= 0) {
                // 当没有与当前视口有相交区域，则将改屏的数据置为该屏的高度占位
                twoList[currentIndex] = { height: pageHeightArr.current[currentIndex] };
                setTwoList(__spread(twoList));
            }
            else if (!((_a = twoList[currentIndex]) === null || _a === void 0 ? void 0 : _a.length)) {
                // 如果有相交区域，则将对应的维度进行赋值
                twoList[currentIndex] = initList.current[currentIndex];
                setTwoList(__spread(twoList));
            }
        });
    };
    return [twoList];
}
